package com.ruoyi.table.service.impl;

import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.catering.common.seller.context.SellerContextHolder;
import com.ruoyi.table.domain.DiningTable;
import com.ruoyi.table.domain.TableArea;
import com.ruoyi.table.mapper.TableAreaMapper;
import com.ruoyi.table.service.DiningTableService;
import com.ruoyi.table.service.TableAreaService;
import com.ruoyi.common.core.utils.FastIDUtil;
import com.ruoyi.common.core.web.domain.BaseEntity;
import com.ruoyi.common.mybatis.core.page.PageQuery;
import com.ruoyi.common.mybatis.core.page.TableDataInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * 表区域服务impl
 *
 * @author Administrator
 * @date 2023/03/06
 */
@Service
@RequiredArgsConstructor
public class TableAreaServiceImpl extends ServiceImpl<TableAreaMapper, TableArea> implements TableAreaService {

    private final DiningTableService diningTableService;

    /**
     * 列表页表区域
     *
     * @param tableArea 表区域
     * @param pageQuery 页面查询
     * @return {@link TableDataInfo}<{@link TableArea}>
     */
    @Override
    public TableDataInfo<TableArea> pageTableArea(TableArea tableArea, PageQuery pageQuery) {
        return TableDataInfo.build(baseMapper.selectPage(pageQuery.build(), Wrappers.lambdaQuery(TableArea.class)
            .orderByDesc(BaseEntity::getUpdateTime)));
    }


    @Override
    public boolean updateStatus(TableArea tableArea) {
        if (ObjUtil.equals(tableArea.getStatus(), 0)) {
            long useCount = diningTableService.countUsing(
                tableArea.getAreaId()
            );
            if (useCount > 0L) {
                return false;
            }
        }
        baseMapper.updateById(tableArea);
        return true;
    }

    @Override
    public int saveTableArea(TableArea tableArea) {
        tableArea.setAreaNo(FastIDUtil.randomTimeId());
        tableArea.setSellerId(SellerContextHolder.getRequiredSellerId());
        tableArea.setStatus(1);
        return baseMapper.insert(tableArea);
    }

    @Override
    public boolean deleteTableAreaById(Long areaId) {
        long count = diningTableService.count(Wrappers.lambdaQuery(DiningTable.class).eq(DiningTable::getAreaId, areaId));
        if (count == 0L) {
            baseMapper.deleteById(areaId);
            return true;
        }
        return false;
    }
}
